export const BASE_URL = "http://192.168.1.4:9001";
// export const BASE_URL = "https://xmk.ahshenmeng.com/api";

export const Request = (params) => {
	console.log("请求开始");
	let url = `${BASE_URL}${params.url}`;
	let method = params.method || "GET";
	let data = params.data || {};
	let headers = {
		'Authorization': `Bearer ${uni.getStorageSync("token")}`,
		'Content-Type': 'application/json;charset=UTF-8'
	};

	// 如果是 POST 请求，则设置 Content-Type 为 application/json
	if (method.toLowerCase() === "post") {
		headers['Content-Type'] = 'application/json';
	}

	// 合并用户提供的额外头部信息
	headers = {
		...headers,
		...params.header
	};

	return new Promise((resolve, reject) => {

		uni.showLoading({
			title: "加载中"
		});
		uni.request({
			url: url,
			data: data,
			method: method,
			header: headers,
			success(response) {
				const res = response.data;
				console.log("结果", res);
				// 根据返回的状态码做出对应的操作
				if (res.code === 200) {
					resolve(res);
				} else {
					handleErrorResponse(res);
					reject(res);
				}
			},
			fail(err) {
				console.log('错误', err);
				handleNetworkError(err);
				reject(err);
			},
			complete() {
				console.log('请求结束');
				// 不管成功还是失败都会执行
				uni.hideLoading();
			}
		});
	});
};

// 错误处理函数
const handleErrorResponse = (res) => {
	console.log("handleErrorResponse", res.code);
	switch (res.code) {
		case 401:
			uni.showModal({
				title: "提示",
				content: "请登录",
				showCancel: false,
				success() {
					uni.navigateTo({
						url: "/pages/login/login",
					});
				},
			});
			break;
		case 404:
			uni.showToast({
				title: '请求地址不存在...',
				duration: 2000,
				icon: 'none',
			});
			break;
		case 400:
			uni.showToast({
				title: res.msg,
				icon: 'none',
				duration: 2000,
			});
			break;
		case 501:
			uni.showToast({
				title: res.msg,
				icon: 'none',
				duration: 2000,
			});
			break;
		case 500:
			uni.showToast({
				title: res.msg,
				icon: 'none',
				duration: 2000,
			});
			break;
		case 'SUCCESS':
			uni.showToast({
				title: '成功',
				icon: 'none',
				duration: 2000,
			});
			break;
		default:
			uni.showToast({
				title: '未知错误，请重试...',
				duration: 2000,
				icon: 'none',
			});
			break;
	}
};

// 网络错误处理函数
const handleNetworkError = (err) => {
	if (err.errMsg == 'request:fail timeout') {
		uni.showToast({
			title: '请求超时',
			icon: "error",
			duration: 2000
		});
	} else {
		uni.showToast({
			title: '请求失败',
			duration: 2000,
			icon: "error",
		});
	}
};